package logic

import (
	"context"
	"fmt"
	"gozerogateway/rpc/common"
	"gozerogateway/rpc/svc/service"
	"strings"

	"gozerogateway/rpc/svc/internal/svc"
	"gozerogateway/rpc/svc/svcclient"

	"encoding/json"
	"github.com/zeromicro/go-zero/core/logx"
)

type ServiceListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewServiceListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ServiceListLogic {
	return &ServiceListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ServiceListLogic) ServiceList(in *svcclient.ServiceListReq, gatewayparm ...string) (*svcclient.ServiceListResp, error) {
	// todo: add your logic here and delete this line

	all, err := l.svcCtx.SvcModel.FindAll(l.ctx, in, in.PageNo, in.PageSize) //Pageno Current
	count, _ := l.svcCtx.SvcModel.Count(l.ctx)
	if err != nil {
		reqStr, _ := json.Marshal(in)
		logx.WithContext(l.ctx).Errorf("分页查询所有信息失败,参数:%s,异常:%s", reqStr, err.Error())
		return nil, err
	}

	var outList []*service.ServiceListItemResp
	for _, servicelist := range *all {
		serviceDetail, err := l.ServiceDetail(&servicelist)
		if err != nil {
			logx.WithContext(l.ctx).Errorf("servicedetail error")
			return nil, err
		}

		//SerceAddr
		//1 http:gatewayip+gatewayport+gatewaypath
		//2 http:domain
		//3 tcpgrpc:gatewayip+serviceport
		serviceAddr := "unknow"
		gatewayIP := "127.0.0.1"
		gatewayPort := "8880"
		gatewaySSLPort := "4880"

		gatewayIP = gatewayparm[0]
		gatewayPort = gatewayparm[1]
		gatewaySSLPort = gatewayparm[2]

		if serviceDetail.Info.LoadType == common.LoadTypeHTTP && serviceDetail.HTTPRule.RuleType == common.HTTPRuleTypePrefixURL && serviceDetail.HTTPRule.NeedHttps == 1 {
			serviceAddr = fmt.Sprintf("%s:%s%s", gatewayIP, gatewaySSLPort, serviceDetail.HTTPRule.Rule)
		}

		if serviceDetail.Info.LoadType == common.LoadTypeHTTP && serviceDetail.HTTPRule.RuleType == common.HTTPRuleTypePrefixURL && serviceDetail.HTTPRule.NeedHttps == 0 {
			serviceAddr = fmt.Sprintf("%s:%s%s", gatewayIP, gatewayPort, serviceDetail.HTTPRule.Rule)
		}

		if serviceDetail.Info.LoadType == common.LoadTypeHTTP && serviceDetail.HTTPRule.RuleType == common.HTTPRuleTypeDomain {
			serviceAddr = serviceDetail.HTTPRule.Rule
		}

		if serviceDetail.Info.LoadType == common.LoadTypeTCP {
			serviceAddr = fmt.Sprintf("%s:%d", gatewayIP, serviceDetail.TCPRule.Port)
		}

		if serviceDetail.Info.LoadType == common.LoadTypeGRPC {
			serviceAddr = fmt.Sprintf("%s:%d", gatewayIP, serviceDetail.GRPCRule.Port)
		}
		ipList := len(strings.Split(serviceDetail.LoadBalance.IpList, ","))
		outItem := &service.ServiceListItemResp{
			ID:          servicelist.Id,
			ServiceName: servicelist.ServiceName,
			ServiceDesc: servicelist.ServiceDesc,
			LoadType:    servicelist.LoadType, //负载类型 0=http 1=tcp 2=grpc
			ServiceAddr: serviceAddr,
			Qps:         0,
			Qpd:         0,
			TotalNode:   int64(ipList),
		}
		outList = append(outList, outItem)
		//list = append(list, &service.ServiceListItemResp{
		//ID          int64  `protobuf:"varint,1,opt,name=ID,proto3" json:"ID,omitempty"`
		//ServiceName string `protobuf:"bytes,2,opt,name=ServiceName,proto3" json:"ServiceName,omitempty"`
		//ServiceDesc string `protobuf:"bytes,3,opt,name=ServiceDesc,proto3" json:"ServiceDesc,omitempty"`
		//LoadType    int64  `protobuf:"varint,4,opt,name=LoadType,proto3" json:"LoadType,omitempty"`
		//ServiceAddr string `protobuf:"bytes,5,opt,name=ServiceAddr,proto3" json:"ServiceAddr,omitempty"`
		//Qps         int64  `protobuf:"varint,6,opt,name=Qps,proto3" json:"Qps,omitempty"`
		//Qpd         int64  `protobuf:"varint,7,opt,name=Qpd,proto3" json:"Qpd,omitempty"`
		//TotalNode   int64  `protobuf:"varint,8,opt,name=TotalNode,proto3" json:"TotalNode,omitempty"`

		//ID:          servicelist.Id,
		//ServiceName: servicelist.ServiceName,
		//ServiceDesc: servicelist.ServiceDesc,
		//LoadType:    servicelist.LoadType,
		//})
	}

	reqStr, _ := json.Marshal(in)
	listStr, _ := json.Marshal(outList)
	logx.WithContext(l.ctx).Infof("分页查询所有信息,参数：%s,响应：%s", reqStr, listStr)
	return &service.ServiceListResp{
		Total: count,
		List:  outList,
	}, nil

}
